/**
 * @ Author: luoqi
 * @ Create Time: 2025-05-21 10:04
 * @ Modified by: luoqi
 * @ Modified time: 2025-06-23 15:36
 * @ Description:
 */

#pragma once

#ifndef _JCONFIG_HPP_
#define _JCONFIG_HPP_

#include <filesystem>
#include <fstream>
#include <logger.hpp>
#include "nlohmann/json.hpp"

namespace fs = std::filesystem;

class JConfig {
public:
    using json = nlohmann::ordered_json;

private:
    const fs::path cfg_dir = ".config";
    fs::path cfg_file;
    json cfg;

public:
    QLog::Logger &logger = LoggerObj::obj();

    JConfig(fs::path cfg_name)
    {

        if(!fs::exists(cfg_dir)) {
            logger.warn_c("config dir not exist, create it <path: \"{}\">", cfg_dir.string().c_str());
            fs::create_directory(cfg_dir);
        }

        cfg_file = cfg_dir / cfg_name;
        if(!fs::exists(cfg_file)) {
            logger.warn_c("\"{}\" file not exist, create it <path: \"{}\">", cfg_name.string().c_str(), cfg_file.string().c_str());
            std::ofstream ofs(cfg_file);
            ofs << cfg.dump(4) << std::endl;
            ofs.close();
        }
    }
    ~JConfig() = default;

    json &load()
    {
        std::ifstream ifs(cfg_file);
        ifs >> cfg;
        ifs.close();
        return cfg;
    }

    void update()
    {
        std::ofstream ofs(cfg_file);
        ofs << cfg.dump(4) << std::endl;
        ofs.close();
    }

    void update(const json &cfg)
    {
        this->cfg = cfg;
        update();
    }

    bool empty()
    {
        std::ifstream ifs(cfg_file);
        ifs >> cfg;
        return cfg.empty();
    }
};

#endif
